# Create your views here.

from table import models
from django.http import request,HttpResponse
from django.shortcuts import render

def add_book_121(request):
    '''一对多'''
    # 方式一：传对象的形式
    # publish_obj = models.Publish.objects.filter(pk=1).first()
    # book = models.Book.objects.create(title="田野之歌",price=46.20,pub_date="2006-12-06",publish=publish_obj)

    # 方式二：传字段方式
    publish_obj = models.Publish.objects.filter(pk=1).first()
    pk = publish_obj.pk
    book = models.Book.objects.create(title="田野之歌",price=46.20,pub_date="2006-12-06",publish_id=pk)
    print(book,type(book))  # Book object (2) <class 'table.models.Book'>

    return HttpResponse(book)

def add_book_m2m(request):
    '''多对多'''
    # 方式一：传对象形式
    # zimei = models.Author.objects.filter(name="子美").first()
    # qingfeng = models.Author.objects.filter(name="清风").first()
    # book = models.Book.objects.filter(title="田野之歌").first()
    # book.authors.add(zimei,qingfeng)

    # 方式二：id形式
    zimei = models.Author.objects.filter(name="清风").first()
    pk = zimei.pk
    book = models.Book.objects.filter(title="田野之歌").first()
    book.authors.add(pk)
    return HttpResponse(book)

def rele_manager_forward(request):
    '''
    关联管理器（正向）
    关联管理器前提：
    多对多（双向均有关联管理器）
    一对多（只有多的那个类的对象有关联管理器，即反向才有）
    '''
    # 方式一：传对象
    # book_obj = models.Book.objects.get(id=2)
    # author_list = models.Author.objects.filter(id__gte=2)
    # book_obj.authors.add(*author_list)

    # 方式二：id形式
    book_obj = models.Book.objects.get(id=2)
    # 将id=1 id=3加入集合
    book_obj.authors.add(*[1,3])

    return HttpResponse(book_obj)

def rele_manage_reverse(request):
    '''
    关联管理器(反向)
    小写表名_set
    '''
    zimei = models.Author.objects.filter(name="子美").first()
    book = models.Book.objects.filter(title="人间四月").first()
    zimei.book_set.add(book)
    return HttpResponse(book)

def index_no_name(request,year):
    '''
    正则路径中的无名分组
    一个形参代表路径中一个分组的内容，按顺序匹配
    http://127.0.0.1:8000/index/2002/
    '''
    print(year)
    return HttpResponse(year)

def index_has_name(request,year,month):
    '''
    有名分组
        http://127.0.0.1:8000/index/2002/02/
    '''
    return HttpResponse(year,month)
